﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;

namespace PersonalTrener
{
    public partial class mainForm : Form, XmlWork.IXmlWorker
    {
        private const string CONFIG_FILENAME = "Config.xml";
        public mainForm()
        {
            InitializeComponent();
        }

        private void mainForm_Load(object sender, EventArgs e)
        {
            m_ObjectName = "Персональный тренер v1.0";
            saveButton.Enabled = false;
            trayNotifyIcon.Text = Text;
            soundPathTextBox.Text = "Message.wav";
            picPathTextBox.Text = "Pic.jpg";

            XmlWork.WorkWithXML.ReadFromXmlFile(CONFIG_FILENAME, this);
            if (minimizeCheckBox.Checked)
                this.WindowState = FormWindowState.Minimized;
            SetTime();
        }

        private void trayNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = true;
                this.ShowInTaskbar = true;
                this.WindowState = FormWindowState.Normal;
            }
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                this.Visible = false;
            }
        }

        private List<DateTime> m_Time = new List<DateTime>();
        private void SetTime()
        {
            playTimer.Enabled = false;
            m_Time.Clear();
            try
            {
                foreach (string s in timeListBox.Items)
                {
                    m_Time.Add(DateTime.Parse(s));
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Ошибка значений в списке: "+e.Message);
            }
            timeListBox.Enabled = false;
            newTimeTextBox.Enabled = false;
            addNewTimeButton.Enabled = false;
            delSelectedTimeButton.Enabled = false;
            playTimer.Enabled = true;
        }

        private void playTimer_Tick(object sender, EventArgs e)
        {
            foreach (var item in m_Time)
            {
                DateTime tNow = DateTime.Now;
                if (tNow < item && tNow.AddSeconds(1) >= item)
                {
                    DoAlarm();
                }
            }
        }

        private void DoAlarm()
        {
            
            if (playSoundCheckBox.Checked)
            {
                SoundPlayer player = new SoundPlayer();
                player.SoundLocation = soundPathTextBox.Text;
                player.Play();
            }
            if (showPicCheckBox.Checked)
            {
                picAlarm.ShowAlarm(picPathTextBox.Text);
            }
        }

        private void soundPathTextBox_Click(object sender, EventArgs e)
        {
            if (picsoundOpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string oldVal = soundPathTextBox.Text;
                soundPathTextBox.Text = picsoundOpenFileDialog.FileName;
                if (oldVal != soundPathTextBox.Text)
                    saveButton.Enabled = true;
            }
        }

        private void picPathTextBox_Click(object sender, EventArgs e)
        {
            if (picsoundOpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string oldVal = picPathTextBox.Text;
                picPathTextBox.Text = picsoundOpenFileDialog.FileName;
                if (oldVal != picPathTextBox.Text)
                    saveButton.Enabled = true;
            }
        }

        private void editButton_Click(object sender, EventArgs e)
        {
            if (editButton.Text == "Редактировать время")
            {
                timeListBox.Enabled = true;
                newTimeTextBox.Enabled = true;
                addNewTimeButton.Enabled = true;
                delSelectedTimeButton.Enabled = true;
                editButton.Text = "Установить время";
            }
            else
            {
                SetTime();
                saveButton.Enabled = true;
                editButton.Text = "Редактировать время";
            }
        }

        private void setupButton_Click(object sender, EventArgs e)
        {
            if (timeListBox.SelectedIndex >= 0)
                timeListBox.Items.RemoveAt(timeListBox.SelectedIndex);
        }

        private void addNewTimeButton_Click(object sender, EventArgs e)
        {

            if (!timeListBox.Items.Contains(newTimeTextBox.Text))
                timeListBox.Items.Add(newTimeTextBox.Text);
        }


        public void SaveToFile(System.Xml.XmlTextWriter xmlOut)
        {
            xmlOut.WriteStartElement("PersonalTrener");
            xmlOut.WriteAttributeString("Minimize", minimizeCheckBox.Checked.ToString());
            xmlOut.WriteAttributeString("PlaySound", playSoundCheckBox.Checked.ToString());
            xmlOut.WriteAttributeString("SoundPath", soundPathTextBox.Text);
            xmlOut.WriteAttributeString("ShowPic", showPicCheckBox.Checked.ToString());
            xmlOut.WriteAttributeString("PicPath", picPathTextBox.Text);
            xmlOut.WriteAttributeString("Time", timeListBox.Items.Cast<string>().Aggregate((a, b) => a + "," + b));
            xmlOut.WriteEndElement();
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            XmlWork.WorkWithXML.SaveToXmlFile(CONFIG_FILENAME, this);
            saveButton.Enabled = false;
        }

        private void minimizeCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            saveButton.Enabled = true;
        }

        private void playSoundCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            saveButton.Enabled = true;
        }

        private void showPicCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            saveButton.Enabled = true;
        }

        private string m_ObjectName;
        public string ObjectName { get { return m_ObjectName; } }


        public void ReadFromFile(System.Xml.XmlTextReader xmlIn)
        {
            try
            {
                if (xmlIn.Name == "PersonalTrener")
                {
                    minimizeCheckBox.Checked = Convert.ToBoolean(xmlIn.GetAttribute("Minimize"));
                    playSoundCheckBox.Checked = Convert.ToBoolean(xmlIn.GetAttribute("PlaySound"));
                    soundPathTextBox.Text = xmlIn.GetAttribute("SoundPath");
                    showPicCheckBox.Checked = Convert.ToBoolean(xmlIn.GetAttribute("ShowPic"));
                    picPathTextBox.Text = xmlIn.GetAttribute("PicPath");
                    timeListBox.Items.Clear();
                    var newListBoxItemsStr = xmlIn.GetAttribute("Time");
                    newListBoxItemsStr.Split(',').ToList().ForEach(item => timeListBox.Items.Add(item));
                }
            }
            catch (Exception)
            { }
        }
    }
}
